﻿using System;
using System.Collections.Generic;
using Object = UnityEngine.Object;

namespace ZyGame.Resource
{
    sealed class RefrenceManager : Singleton<RefrenceManager>
    {
        private List<BundleRefrence> bundles = new List<BundleRefrence>();

        public void Enqueue(BundleRefrence context)
        {
            bundles.Add(context);
        }

        public bool TryOutBundle(string name, out BundleRefrence bundle)
        {
            bundle = bundles.Find(x => x.name == name);
            if (bundle is null)
            {
                if (Client.Cache.TryDequeue(name, out bundle))
                {
                    bundles.Add(bundle);
                }
            }
            return bundle is not null;
        }

        public bool TryOutBundleWithAssetName(string name, out BundleRefrence bundle)
        {
            bundle = bundles.Find(x => x.HasHaveAsset(name));
            if (bundle is null)
            {
                if (Client.Cache.TryDequeue(CheckHaveAsset, out bundle))
                {
                    bundles.Add(bundle);
                }
            }
            bool CheckHaveAsset(BundleRefrence bundle)
            {
                return bundle.HasHaveAsset(name);
            }
            return bundle is not null;
        }

        public bool EnsureAssetBundleLoaded(string name)
        {
            return TryOutBundle(name, out _);
        }

        public void Release(Object context)
        {
            BundleRefrence bundle = bundles.Find(x => x.HasHaveAsset(context));
            if (bundle is null)
            {
                Client.Console.WriteLine($"释放资源，但是没有找到资源所引用的资源包:{context.name}");
                return;
            }
            bundle.Release(context);
            if (bundle.TryUnload() is false)
            {
                return;
            }
            bundles.Remove(bundle);
            Client.Cache.Enqueue(bundle);
        }
    }
}